package net.chat.servlet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.chat.utils.Encryptor;
import net.chat.User;
import net.chat.server.ChatServer;
import net.chat.utils.Util;

/**
 * The UserServlet is used to service requests relating to users.
 * @author Prabhat
 * Implemented 'register', 'delete', 'login' and 'logout' actions.
 * @author Amir added password encryption
 */
public class UserServlet extends HttpServlet {

    private ChatServer server = ChatServer.getInstance();

    /**
     * Handles POST requests to register and login.
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        if (action != null) {
            String redirectUrl = Util.WEBAPP_URL + "stage2/";
            if (action.equals("register")) { // register is done through POST method

                String from = request.getParameter("from");
                redirectUrl += from + ".jsp";

                String fname = request.getParameter("fname");
                String lname = request.getParameter("lname");
                String pwd = request.getParameter("pwd");

                if (fname != null && !fname.isEmpty()
                        && lname != null && !lname.isEmpty()
                        && pwd != null && !pwd.isEmpty()) {

                    User newUser = new User(fname, lname, pwd);
                    server.newUser(newUser); // add new user to server
                    redirectUrl += "?uid=" + newUser.getUid();
                } else {
                    redirectUrl += "?err=u";
                }
                response.sendRedirect(redirectUrl);
            }

            if (action.equals("login")) {
                String uid = request.getParameter("userid");
                String pwd = request.getParameter("password");

                User user = null;
                try {
                    user = server.login(uid, Encryptor.encrypt(pwd));
                } catch (Exception ex) {
                    Logger.getLogger(UserServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
                if (user == null) {
                    redirectUrl += "login.jsp?err=1";
                } else {
                    HttpSession session = request.getSession(); // create user session
                    session.setAttribute(Util.USER_SESS, user);
                    redirectUrl += "forums.jsp";
                }
                response.sendRedirect(redirectUrl);
            }
        }
    }

    /**
     * Handles GET requests to delete and logout.
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        String redirectUrl = Util.WEBAPP_URL + "stage2/";
        if (action != null) {
            String strUid = request.getParameter("uid");
            if (action.equals("delete")) {// register is done through GET method
                String from = request.getParameter("from");
                redirectUrl += from + ".jsp";
                server.deleteUser(Integer.parseInt(strUid));
            }

            if (action.equals("logout")) {
                redirectUrl += "login.jsp";
                server.logout(Integer.parseInt(strUid)); // remove user from any forum
                request.getSession().removeAttribute(Util.USER_SESS);
            }
            response.sendRedirect(redirectUrl);
        }
    }
}
